import { SharedModule } from './../../shared.module';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { ActivatedRoute } from "@angular/router";
import { MdSnackBar } from "@angular/material";
import { MessageBoxService, GrowlMessageType } from './../messageBoxService';
import { Component, Output, EventEmitter, OnInit, Input, NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { SystemService } from "../../service/system.service";
import { NavigateService } from "../../service/navigate.service";
import { QueueManager } from "../../common/queueManager";

@Component({
    selector: 'config-ldc',
    template: `
        <div fxLayout="column" class="fullScreen color-lightblack">
            <header class="app-header noshrink">
                <span class="margin-l">{{title}}</span>
            </header>
            <div *ngIf="mode == 'auto'" fxLayout="column">
                <div class="padding" fxFlex="50%" fxLayoutAlign="start space-between">
                    <div fxLayout="column" fxLayoutAlign="center center" fxFlex="100%">
                        <img class="search-img" src="./assets/images/loading.gif">
                        <span fxFlexAlign="center">正在查找本地数据中心</span>
                    </div>
                </div>
                <div fxFlex="50%" fxLayout="row" class="padding">
                    <button class="bgcolor-primary content-btn color-white text-s pct100" md-button (click)="switchManualMode()">取消</button>
                </div>
            </div>
            <div fxLayout="column" *ngIf="mode == 'manual'">
                <div class="margin" fxFlex="50%">
                    <div>
                        <span class="text-l">手动查找本地数据中心</span>
                        <div class="v-gap-s">
                            <md-input-container class="pct100">
                                <input placeholder="输入IP地址" mdInput [(ngModel)]="IPAddress">
                            </md-input-container>
                            <span *ngIf="!manualSuccess" class="color-warn text-s">不能连接到{{IPManual}}</span>
                            <span *ngIf="manualSuccess">&nbsp;</span>
                        </div>
                    </div>
                    <button class="bgcolor-primary content-btn color-white text-s pct100" md-button (click)="searchLDCManual()">手动查找</button>
                </div>
                <div class="margin" fxLayout="column" fxFlex="50%">
                    <button class="text-s pct100 bgcolor-darkwhite auto-search-btn noshrink" md-button (click)="switchAutoMode()">自动查找</button>
                    <div fxLayout="column" fxLayoutAlign="center start" class="text-s v-gap-s" fxFlex="100%">
                        <span>如何确定本地数据中心IP地址？</span>
                        <span class="v-gap color-lightgray">1、在收银台进入【设置-本地数据中心】</span>
                        <span class="color-lightgray">2、点击【设置本终端为“本地数据中心”主机-勾选门店业务支持（店员宝支持）】</span>
                        <span class="color-lightgray">3、点击确定后在当前页面即可查看IP地址</span>
                    </div>
                </div>
            </div>
        </div>
    `,
    styleUrls: ['./configLDC.component.scss']
})
export class ConfigLDC implements OnInit {
    constructor(
        private sysSvr: SystemService,
        private router: NavigateService,
        private msgSvr: MessageBoxService,
        public snackBar: MdSnackBar,
        private acRouter: ActivatedRoute,
    ) { }
    @Output() searchSuccess: EventEmitter<any> = new EventEmitter<any>();
    @Input() searchMode: string;
    title: string = "查找本地数据中心";
    mode: string = "auto";
    IPAddress: string;
    IPManual: string;
    manualSuccess: boolean = true;
    LDCIPAddress: string;

    ngOnInit() {
        if (this.searchMode == "auto") {
            this.startAutoSearch();
        } else {
            this.switchManualMode();
        }
    }
    /**
     * 切换为手动查找模式
     */
    switchManualMode() {
        this.mode = "manual";
        this.breakOffQueue();
    }

    switchAutoMode() {
        this.mode = "auto";
        this.startAutoSearch();
    }
    /**
     * 手动查找本地数据中心
     */
    async searchLDCManual() {
        let ipRegExp = new RegExp("^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$");
        let boo = ipRegExp.test(this.IPAddress);
        if (!boo) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, "输入的IP地址有误，请重新输入");
            this.IPAddress = "";
            return;
        }
        this.mode = "auto";
        this.manualSuccess = true;
        let ip = this.IPAddress;
        this.IPManual = this.IPAddress;
        if (ip) {
            try {
                let result = await this.sysSvr.checkIsLDC(ip);
                if (result) {
                    this.sysSvr.LDCAddress = ip;
                    this.LDCIPAddress = ip;
                    // this.router.navigate(["checkEnv"]);
                    this.searchSuccess.emit(this.LDCIPAddress);
                }
            } catch (error) {
                this.manualSuccess = false;
                this.mode = "manual";
                console.log(error);
            }
        }
    }

    /**
     * 中断请求队列
     */
    breakOffQueue() {
        QueueManager.Current.BreakOff();
    }

    /**
     * 开始自动查找本地数据中心
     */
    startAutoSearch() {
        this.LDCIPAddress = "";
        if ((<any>window).device) {
            let device = (<any>window).device;
            try {
                let deviceInfo = device.getDeviceInfo();
                if (deviceInfo && deviceInfo.ip) {
                    let ip = deviceInfo.ip;
                    let index = ip.lastIndexOf(".");
                    let ipAhead = ip.substring(0, index);
                    let ipBehind = ip.substring(index + 1, ip.length);
                    for (let i = 0; i < 256; i++) {
                        let targetIP = ipAhead + "." + i;
                        this.addUrlToQueue(targetIP);
                    }
                } else {
                    this.switchManualMode();
                }
            } catch (error) {
                console.log(error);
            }
        } else {
            this.switchManualMode();
        }
    }

    /**
     * 添加url到队列中循环请求
     */
    addUrlToQueue(ip: string) {
        QueueManager.Current.Add((async () => {
            let result = await this.sysSvr.checkIsLDC(ip);
            if (result && !this.LDCIPAddress) {
                this.LDCIPAddress = ip;
                this.sysSvr.LDCAddress = ip;
                this.breakOffQueue();
                // this.router.navigate(["checkEnv"]);
                this.searchSuccess.emit(this.LDCIPAddress);
            }
        }).bind(this))
    }
}

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        SharedModule
    ],
    declarations: [
        ConfigLDC
    ],
    exports: [
        ConfigLDC
    ],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class ConfigLDCModule {

}